package com.example.demo.config;

import com.example.demo.service.JwtService;
import com.example.demo.filter.JwtAuthenticationToken;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;

import feign.RequestInterceptor;
import feign.RequestTemplate;

@Configuration
public class FeignConfig implements RequestInterceptor {
    @Autowired
    private JwtService jwtService;

    @Override
    public void apply(RequestTemplate template) {
        var authentication=jwtService.getAuthentication();
        //只有客户端传递token的时候才去添加
        if (authentication != null){

            //获取token详细信息
            Object details = authentication.getDetails();

            if (details instanceof UserDetails){
                var jwt = ((JwtAuthenticationToken)authentication).getToken();
                //获取token
                String token = jwt.getToken();

                //在feign的请求头中添加token
                template.header("Authorization","Bearer " + token);

            }

        }
    }
    
}
